<template>
  <div>
    <el-checkbox
      :disabled="disabled"
      :indeterminate="indeterminate"
      v-model="checkAll"
      @change="handleCheckAllChange"
    >
      {{ title }}
    </el-checkbox>
    <el-checkbox-group
      :disabled="disabled"
      v-model="allData.sel"
      @change="handleCheckedCitiesChange"
      style="padding-left: 12px"
    >
      <el-checkbox
        v-for="(val, index) in options"
        :label="val.id"
        :key="index"
        name="type"
      >
        {{ val.menuName }}
      </el-checkbox>
    </el-checkbox-group>
  </div>
</template>
<script>
  import { reactive, ref, watch } from 'vue'
  export default {
    name: 'GradeCheckbox',
    props: {
      options: Array,
      modelValue: Array,
      title: String,
      index: Number,
      id: Number,
      disabled: Boolean,
    },
    emits: ['checkChange', 'update:modelValue'],
    setup(props, context) {
      let indeterminate = ref(false)
      let checkAll = ref(false)
      // 选择的选项
      let allData = reactive({ sel: [], values: [] })
      const compensateF = function (values) {
        if (values.length === 1 && values.includes(props.id)) {
          return []
        } else if (values.includes(props.id) && values.length >= 1) {
          return values
        } else if (!values.includes(props.id) && values.length >= 1) {
          return [props.id].concat(values)
        }
        return values
      }

      const handleCheckAllChange = function (val) {
        const value = val ? props.options.map((item) => item.id) : []
        indeterminate.value = false
        context.emit('update:modelValue', compensateF(value))
      }
      const handleCheckedCitiesChange = function (value) {
        const checkedCount = value.length
        checkAll.value = checkedCount === props.options.length + 1
        indeterminate.value =
          checkedCount > 1 && checkedCount < props.options.length + 1
        context.emit('update:modelValue', compensateF(value))
      }
      watch(
        () => props.modelValue,
        (val) => {
          if (val && Array.isArray(val)) {
            allData.sel = val
            handleCheckedCitiesChange(val)
          }
        },
        { immediate: true }
      )
      return {
        indeterminate,
        checkAll,
        allData,
        handleCheckAllChange,
        handleCheckedCitiesChange,
      }
    },
  }
</script>
<style lang="scss" scoped>
  .roleSetting-container {
    .el-checkbox-group {
      padding-left: 12px;
    }
  }
</style>
